package ucl.cs.stockBroker.server;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import ucl.cs.stockBroker.common.StockBroker;

public class Server {
	public Server() {
		try {
			final StockBrokerImpl stockBroker = new StockBrokerImpl();
			StockBroker stub = (StockBroker) UnicastRemoteObject.exportObject(
					stockBroker, 0);

			// Bind the StockBroker's stub in the RMI Registry
			// with the name 'Server' that clients can lookup.
			Registry registry = LocateRegistry.getRegistry();
			registry.rebind("Server", stub);

			Thread thread = new Thread(new ServerReader(stockBroker));
			thread.start();

			Thread stocksThread = new Thread(new Stocks(stockBroker));
			stocksThread.start();

			stockBroker.addListener(new AccountUpdatedListener() {
				public void onEvent() {
					Thread thread = new Thread(new ServerWriter(stockBroker
							.getAccounts()));
					thread.start();
					System.out.println("Backup File Written.");

				}
			});

		} catch (Exception e) {
			System.out.println("Trouble: " + e);
		}

		System.out.println("Server Started.");
	}

	public static void main(String args[]) {
		new Server();
	}
}
